<template>
<div id="forgot">
	<h3 class="auth-title">找回密码</h3>
	<el-form ref="form" :model="form" :rules="rules">
		<el-form-item class="auth-line" prop="email">
			<auth-input icon="icon-email" v-model="form.email" placeholder="请输入电子邮件" />
		</el-form-item>

		<el-form-item class="auth-line" prop="validateCode">
			<auth-input icon="icon-yanzhengma" v-model="form.validateCode" style="width: 60%;float: left;" placeholder="验证码" />
			<el-button type="button"
				style="width: 40%;float: left;"
				class="btn btn-rect auth-btn"
				@click="sendEmail"
				:disabled="timeout > 0">{{timeout == 0 ? '发送邮件' : timeout+'后重发'}}</el-button>
		</el-form-item>

		<el-form-item class="auth-line" prop="newPassword">
			<auth-input icon="icon-mima" v-model="form.newPassword" placeholder="请输入您的新密码"/>
		</el-form-item>

		<button type="button" class="btn btn-rect auth-btn" @click="submit">修改密码</button>
	</el-form>

	<div class="auth-line auth-links">
			<router-link to="login" tag="div" class="pull-left">
				返回登录
			</router-link>
			<router-link to="register" tag="div" class="pull-right">
				注册账号
			</router-link>
		</div>
</div>
</template>

<script>
import api from '~/api/api.js';
import AuthInput from '~/components/AuthInput.vue';

export default {
	components: {
		AuthInput
	},
	data () {
		return {
			timeout: 0,
			form: {
				email: '',
				validateCode: '',
				newPassword: ''
			},
			rules: {
				email: [
					{required: true, message: '请输入电子邮箱'},
					{ pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]{2,4}$/, message: '请输入正确邮箱', trigger: 'blur'}
				],
				validateCode: [
					{required: true, message: '请输入验证码'}
				],
				newPassword: [
					{required: true, message: '请输入密码'},
					{min: 6, message: '密码不能小于六位', trigger: 'blur'}
				]
			}
		}
	},
	methods: {
		sendEmail () {
			if (/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]{2,4}$/.test(this.form.email)) {
				api.post('/forgot/send_email', {
					email: this.form.email
				})
				.then(response => {
					this.$message('发送成功');
				})
				.catch(error => {
					this.$message.error('验证码发送失败');
				})
				this.timeout = 60;
				let stepFn = () => {
					this.timeout--;
					if (this.timeout > 0) {
						setTimeout(stepFn, 1000);
					}
				}
				setTimeout(stepFn, 1000);
			} else {
				this.$message('邮箱格式不正确');
			}
			
		},
		submit () {
			this.$refs['form'].validate(valid => {
				if(!valid) {
					return this.$message('请完善表单');
				}
				api.post('/forgot', this.form)
				.then(response => {
					this.$message.success('修改成功');
					this.$router.push('/auth/login');
				})
			})
		}
	}
}
</script>

<style scoped>
#forgot {
	padding-top: 1px;
	height: 100%;
}
</style>